<?php
require_once dirname(__FILE__) . '/includes/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";

$updir = UPDIR . '/';

$renamed = "0";
$overwrite = "1"; 
$max = 1000000; 

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  //上传文件赋值给$upload_file
  $upload_file = $_FILES['Filedata'];
  //获取文件类型
  $file_info = pathinfo($upload_file['name']);
  //获取文件扩展名
  $file_ext = $file_info['extension'];
  
  //获取客户端参数
  $directoryToUpload = json_decode($_POST['directoryToUpload']);
  $thumbnail = json_decode($_POST['thumbnail']);
  
  //设置上传的路径
  $directoryToUpload = (substr($directoryToUpload, -1, 1) === '/') ? $directoryToUpload : $directoryToUpload . '/';
  $upload_path = $updir . $directoryToUpload;
  
  //建立文件夹
  create($upload_path);
  
  //需要重命名否?
  if($renamed){
    list($usec, $sec) = explode(' ', microtime());
    $upload_file['name'] = substr($usec, 2) . '.' . $file_ext;
    unset($usec);
    unset($sec);
  }
  //设置默认服务端文件名
  $upload_file['filename'] = $upload_path . $upload_file['name'];
  $upload_file['smallname'] = $upload_path . substr($upload_file['name'], 0, strrpos($upload_file['name'], '.')) . '_thumbnail';
  
  //检查文件是否存在
  if (file_exists($upload_file['filename'])) {
    if($overwrite) {
      @unlink($upload_file['filename']);
    } else {
      $j = 0;
      do {
        $j++;
        $temp_file = str_replace('.' . $file_ext, '('.$j.').' . $file_ext,$upload_file['filename']);
      }
      while (file_exists($temp_file));
      $upload_file['filename'] = $temp_file;
      unset($temp_file);
      unset($j);
    }
  }

  if ($upload_file['size'] && $upload_file['size'] < $max && $thumbnail) {
    if (strtolower($file_ext) == 'jpg' || strtolower($file_ext) == 'jpeg') {
      $im = imagecreatefromjpeg($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'png') {
      $im = imagecreatefrompng($upload_file["tmp_name"]);
    } else if (strtolower($file_ext) == 'gif') {
      $im = imagecreatefromgif($upload_file["tmp_name"]);
    }
    if ($im) {
      $width = imagesx($im);
      $height = imagesy($im);
      
      if (file_exists($upload_file['smallname'])) {
        unlink($upload_file['smallname']);
      }
      ResizeImage($im, 50, 50, $upload_file['smallname']);
      ImageDestroy($im);
    } else {
      exit(0);
    }
  }
  
  if (move_uploaded_file($upload_file['tmp_name'], $upload_file['filename'])) {
    //Add custom code here...;
    $orm = classToOrm('file');
    if ($orm) {
      try {
        $myManager->start_t();
        $file = new stdClass();
        $file->name = substr(strrchr($upload_file['filename'], '/'), 1);
        $file->size = ($upload_file['size']) ? $upload_file['size'] : 0;
        $file->width = (isset($width)) ? $width : 0;
        $file->height = (isset($height)) ? $height : 0;
        $file->thumbnail = ($upload_file['size'] && $upload_file['size'] < $max && $thumbnail) ? substr(strrchr($upload_file['smallname'] . '.jpg', '/'), 1) : '';
        $file->path = $upload_path;
        $epObject = $orm->add($myManager, $file);
        $myManager->commit_t();
        $file = $orm->__toObject($myManager, $epObject, new stdClass());
        echo json_encode($file);
      } catch (PDOException $e) {
        echo $e->getMessage();
      }
    }
  }
} 
  
//若没有这个文件夹，则需要创建文件夹
function create($dir) {
  if (!is_dir($dir)) {
    $temp = explode('/',$dir);
    $cur_dir = '';
    for($i = 0; $i < count($temp); $i++) {
      $cur_dir .= $temp[$i].'/';
      if (!is_dir($cur_dir)) {
        @mkdir($cur_dir, 0777);
      }
    }
  }
}

function ResizeImage($im, $maxwidth, $maxheight, $name){
  $width = imagesx($im);
  $height = imagesy($im);
  if (($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)) {
    $RESIZEWIDTH = false;
    $RESIZEHEIGHT = false;
    if ($maxwidth && $width > $maxwidth) {
      $widthratio = $maxwidth/$width;
      $RESIZEWIDTH = true;
    }
    if ($maxheight && $height > $maxheight) {
      $heightratio = $maxheight/$height;
      $RESIZEHEIGHT = true;
    }
    if ($RESIZEWIDTH && $RESIZEHEIGHT) {
      if ($widthratio < $heightratio) {
        $ratio = $widthratio;
      } else {
        $ratio = $heightratio;
      }
    } else if ($RESIZEWIDTH) {
      $ratio = $widthratio;
    } else if ($RESIZEHEIGHT) {
      $ratio = $heightratio;
    }
    $newwidth = $width * $ratio;
    $newheight = $height * $ratio;
    if (function_exists("imagecopyresampled")) {
      $newim = imagecreatetruecolor($newwidth, $newheight);
      imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    } else {
      $newim = imagecreate($newwidth, $newheight);
      imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    }
    imagejpeg($newim, $name . ".jpg");
    imagedestroy($newim);
  } else {
    imagejpeg($im, $name . ".jpg");
  }
}
?>